﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using System.Net;
using System.Threading.Tasks;

namespace LmgCMS.Middleware {
    public class CorsMiddleware {
        private readonly RequestDelegate _next;
        private readonly IMemoryCache _cache;
        private readonly ILogger<CorsMiddleware> _logger;

        public CorsMiddleware(RequestDelegate next, IMemoryCache cache, ILogger<CorsMiddleware> logger) {
            _next = next;
            _cache = cache;
            _logger = logger;
        }
        public async Task InvokeAsync(HttpContext context) {
            if(context.Request.Headers.ContainsKey(CorsConstants.Origin) || context.Request.Headers.ContainsKey("origin")) {
                if(!context.Request.Headers.TryGetValue(CorsConstants.Origin, out var origin)) {
                    context.Request.Headers.TryGetValue("origin", out origin);
                }

                context.Response.Headers.Add(CorsConstants.AccessControlAllowOrigin, origin);
                context.Response.Headers.Add(
                    CorsConstants.AccessControlAllowHeaders,
                    $"{HeaderNames.Authorization}, {HeaderNames.ContentType}, {HeaderNames.AcceptLanguage}, {HeaderNames.Accept}");
                context.Response.Headers.Add(CorsConstants.AccessControlAllowMethods, "POST, GET, PUT, PATCH, DELETE, OPTIONS");

                if(context.Request.Method == "OPTIONS") {
                    _logger.LogInformation("CORS with origin {Origin} was handled successfully", origin);
                    context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                    return;
                }

                await _next(context);

            }

            await _next(context);
        }

    }
    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class CorsMiddlewareExtensions {
        public static IApplicationBuilder UseMyCors(this IApplicationBuilder builder) {
            return builder.UseMiddleware<CorsMiddleware>();
        }
    }
}
